<template>
  <div class="statistics-page">
    <!-- 页面标题 -->
    <t-card class="header-card">
      <div class="card-header">
        <h2 class="page-title">数据统计</h2>
        <div class="period-selector">
          <t-radio-group v-model="periodType" variant="default-filled" size="medium">
            <t-radio-button value="week">本周</t-radio-button>
            <t-radio-button value="month">本月</t-radio-button>
            <t-radio-button value="year">本年</t-radio-button>
          </t-radio-group>
        </div>
      </div>
    </t-card>
    
    <!-- 数据概览卡片 -->
    <div class="overview-section">
      <t-row :gutter="[16, 16]">
        <t-col :xs="24" :sm="12" :md="6">
          <t-card class="stat-card" hover-shadow>
            <div class="stat-card-content">
              <div class="stat-card-header">
                <div class="stat-card-title">用户总数</div>
                <t-icon name="user" class="stat-card-icon" />
              </div>
              <div class="stat-card-value">
                {{ formatNumber(overviewData.userCount) }}
              </div>
              <div class="stat-card-footer">
                <div class="stat-trend" :class="overviewData.userGrowth >= 0 ? 'up' : 'down'">
                  <t-icon :name="overviewData.userGrowth >= 0 ? 'arrow-up' : 'arrow-down'" />
                  <span>{{ Math.abs(overviewData.userGrowth) }}%</span>
                </div>
                <div class="stat-period">较上一{{ getPeriodText() }}</div>
              </div>
            </div>
          </t-card>
        </t-col>
        
        <t-col :xs="24" :sm="12" :md="6">
          <t-card class="stat-card" hover-shadow>
            <div class="stat-card-content">
              <div class="stat-card-header">
                <div class="stat-card-title">内容总数</div>
                <t-icon name="file" class="stat-card-icon" />
              </div>
              <div class="stat-card-value">
                {{ formatNumber(overviewData.articleCount + overviewData.activityCount + overviewData.spotCount) }}
              </div>
              <div class="stat-card-footer">
                <div class="stat-detail">
                  <span>文章: {{ formatNumber(overviewData.articleCount) }}</span>
                  <span>活动: {{ formatNumber(overviewData.activityCount) }}</span>
                  <span>景点: {{ formatNumber(overviewData.spotCount) }}</span>
                </div>
              </div>
            </div>
          </t-card>
        </t-col>
        
        <t-col :xs="24" :sm="12" :md="6">
          <t-card class="stat-card" hover-shadow>
            <div class="stat-card-content">
              <div class="stat-card-header">
                <div class="stat-card-title">订单总数</div>
                <t-icon name="shop" class="stat-card-icon" />
              </div>
              <div class="stat-card-value">
                {{ formatNumber(overviewData.orderCount) }}
              </div>
              <div class="stat-card-footer">
                <div class="stat-detail">
                  <span>新增: {{ formatNumber(overviewData.newOrderCount) }}</span>
                </div>
              </div>
            </div>
          </t-card>
        </t-col>
        
        <t-col :xs="24" :sm="12" :md="6">
          <t-card class="stat-card" hover-shadow>
            <div class="stat-card-content">
              <div class="stat-card-header">
                <div class="stat-card-title">订单金额</div>
                <t-icon name="money-circle" class="stat-card-icon" />
              </div>
              <div class="stat-card-value">
                ¥{{ formatNumber(overviewData.orderAmount) }}
              </div>
              <div class="stat-card-footer">
                <div class="stat-trend" :class="overviewData.orderAmountGrowth >= 0 ? 'up' : 'down'">
                  <t-icon :name="overviewData.orderAmountGrowth >= 0 ? 'arrow-up' : 'arrow-down'" />
                  <span>{{ Math.abs(overviewData.orderAmountGrowth) }}%</span>
                </div>
                <div class="stat-period">较上一{{ getPeriodText() }}</div>
              </div>
            </div>
          </t-card>
        </t-col>
      </t-row>
    </div>
    
    <!-- 趋势图表区域 -->
    <div class="charts-section">
      <t-row :gutter="[16, 16]">
        <t-col :xs="24" :md="12">
          <t-card title="用户增长趋势" class="chart-card">
            <user-trend-chart :data="userTrendData" :loading="userTrendLoading" />
          </t-card>
        </t-col>
        
        <t-col :xs="24" :md="12">
          <t-card title="订单统计" class="chart-card">
            <order-stats-chart :data="orderStatsData" :loading="orderStatsLoading" />
          </t-card>
        </t-col>
      </t-row>
    </div>
    
    <!-- 内容统计区域 -->
    <div class="content-stats-section">
      <t-row :gutter="[16, 16]">
        <t-col :xs="24" :md="8">
          <t-card title="文章分类统计" class="chart-card">
            <content-category-chart content-type="article" :data="articleCategoryData" :loading="articleCategoryLoading" />
          </t-card>
        </t-col>
        
        <t-col :xs="24" :md="8">
          <t-card title="活动分类统计" class="chart-card">
            <content-category-chart content-type="activity" :data="activityCategoryData" :loading="activityCategoryLoading" />
          </t-card>
        </t-col>
        
        <t-col :xs="24" :md="8">
          <t-card title="景点分类统计" class="chart-card">
            <content-category-chart content-type="spot" :data="spotCategoryData" :loading="spotCategoryLoading" />
          </t-card>
        </t-col>
      </t-row>
    </div>
    
    <!-- 热门内容区域 -->
    <div class="popular-content-section">
      <t-row :gutter="[16, 16]">
        <t-col :xs="24" :md="12">
          <t-card title="热门活动排行" class="list-card">
            <popular-activities-list :data="popularActivitiesData" :loading="popularActivitiesLoading" />
          </t-card>
        </t-col>
        
        <t-col :xs="24" :md="12">
          <t-card title="热门景点排行" class="list-card">
            <popular-spots-list :data="popularSpotsData" :loading="popularSpotsLoading" />
          </t-card>
        </t-col>
      </t-row>
    </div>
    
    <!-- 用户分布区域 -->
    <div class="user-distribution-section">
      <t-row :gutter="[16, 16]">
        <t-col :xs="24" :md="12">
          <t-card title="用户性别分布" class="chart-card">
            <user-gender-chart :data="userGenderData" :loading="userGenderLoading" />
          </t-card>
        </t-col>
        
        <t-col :xs="24" :md="12">
          <t-card title="用户年龄分布" class="chart-card">
            <user-age-chart :data="userAgeData" :loading="userAgeLoading" />
          </t-card>
        </t-col>
      </t-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import {
  getOverviewData,
  getUserTrend,
  getContentTrend,
  getOrderStats,
  getUserGenderDistribution,
  getUserAgeDistribution,
  getContentCategoryStats,
  getPopularActivities,
  getPopularSpots,
  type OverviewData,
  type TrendData,
  type OrderStatData,
  type UserGenderData,
  type UserAgeData,
  type ContentStats,
  type PopularActivity,
  type PopularSpot
} from '../../api/statistics'

// 导入图表组件
import UserTrendChart from './components/UserTrendChart.vue'
import OrderStatsChart from './components/OrderStatsChart.vue'
import ContentCategoryChart from './components/ContentCategoryChart.vue'
import PopularActivitiesList from './components/PopularActivitiesList.vue'
import PopularSpotsList from './components/PopularSpotsList.vue'
import UserGenderChart from './components/UserGenderChart.vue'
import UserAgeChart from './components/UserAgeChart.vue'

// 时间周期
const periodType = ref<'week' | 'month' | 'year'>('month')

// 概览数据
const overviewData = reactive<OverviewData>({
  userCount: 0,
  articleCount: 0,
  activityCount: 0,
  spotCount: 0,
  orderCount: 0,
  orderAmount: 0,
  orderAmountGrowth: 0,
  userGrowth: 0,
  newOrderCount: 0
})

// 趋势数据
const userTrendData = ref<TrendData[]>([])
const userTrendLoading = ref(false)

// 订单统计数据
const orderStatsData = ref<OrderStatData[]>([])
const orderStatsLoading = ref(false)

// 内容分类数据
const articleCategoryData = ref<ContentStats[]>([])
const articleCategoryLoading = ref(false)
const activityCategoryData = ref<ContentStats[]>([])
const activityCategoryLoading = ref(false)
const spotCategoryData = ref<ContentStats[]>([])
const spotCategoryLoading = ref(false)

// 热门内容数据
const popularActivitiesData = ref<PopularActivity[]>([])
const popularActivitiesLoading = ref(false)
const popularSpotsData = ref<PopularSpot[]>([])
const popularSpotsLoading = ref(false)

// 用户分布数据
const userGenderData = ref<UserGenderData[]>([])
const userGenderLoading = ref(false)
const userAgeData = ref<UserAgeData[]>([])
const userAgeLoading = ref(false)

// 初始化
onMounted(() => {
  fetchAllData()
})

// 监听周期变化
watch(periodType, () => {
  fetchAllData()
})

// 获取所有数据
const fetchAllData = () => {
  fetchOverviewData()
  fetchUserTrend()
  fetchOrderStats()
  fetchContentCategories()
  fetchPopularContent()
  fetchUserDistribution()
}

// 获取概览数据
const fetchOverviewData = async () => {
  try {
    const { data } = await getOverviewData()
    if (data) {
      Object.assign(overviewData, data)
    }
  } catch (error) {
    console.error('获取概览数据失败', error)
    MessagePlugin.error('获取概览数据失败')
  }
}

// 获取用户趋势
const fetchUserTrend = async () => {
  userTrendLoading.value = true
  try {
    const { data } = await getUserTrend(periodType.value)
    userTrendData.value = data || []
  } catch (error) {
    console.error('获取用户趋势失败', error)
  } finally {
    userTrendLoading.value = false
  }
}

// 获取订单统计
const fetchOrderStats = async () => {
  orderStatsLoading.value = true
  try {
    const { data } = await getOrderStats(periodType.value)
    orderStatsData.value = data || []
  } catch (error) {
    console.error('获取订单统计失败', error)
  } finally {
    orderStatsLoading.value = false
  }
}

// 获取内容分类统计
const fetchContentCategories = async () => {
  // 获取文章分类统计
  articleCategoryLoading.value = true
  try {
    const { data } = await getContentCategoryStats('article')
    articleCategoryData.value = data || []
  } catch (error) {
    console.error('获取文章分类统计失败', error)
  } finally {
    articleCategoryLoading.value = false
  }
  
  // 获取活动分类统计
  activityCategoryLoading.value = true
  try {
    const { data } = await getContentCategoryStats('activity')
    activityCategoryData.value = data || []
  } catch (error) {
    console.error('获取活动分类统计失败', error)
  } finally {
    activityCategoryLoading.value = false
  }
  
  // 获取景点分类统计
  spotCategoryLoading.value = true
  try {
    const { data } = await getContentCategoryStats('spot')
    spotCategoryData.value = data || []
  } catch (error) {
    console.error('获取景点分类统计失败', error)
  } finally {
    spotCategoryLoading.value = false
  }
}

// 获取热门内容
const fetchPopularContent = async () => {
  // 获取热门活动
  popularActivitiesLoading.value = true
  try {
    const { data } = await getPopularActivities(5)
    popularActivitiesData.value = data || []
  } catch (error) {
    console.error('获取热门活动失败', error)
  } finally {
    popularActivitiesLoading.value = false
  }
  
  // 获取热门景点
  popularSpotsLoading.value = true
  try {
    const { data } = await getPopularSpots(5)
    popularSpotsData.value = data || []
  } catch (error) {
    console.error('获取热门景点失败', error)
  } finally {
    popularSpotsLoading.value = false
  }
}

// 获取用户分布
const fetchUserDistribution = async () => {
  // 获取用户性别分布
  userGenderLoading.value = true
  try {
    const { data } = await getUserGenderDistribution()
    userGenderData.value = data || []
  } catch (error) {
    console.error('获取用户性别分布失败', error)
  } finally {
    userGenderLoading.value = false
  }
  
  // 获取用户年龄分布
  userAgeLoading.value = true
  try {
    const { data } = await getUserAgeDistribution()
    userAgeData.value = data || []
  } catch (error) {
    console.error('获取用户年龄分布失败', error)
  } finally {
    userAgeLoading.value = false
  }
}

// 获取周期文本
const getPeriodText = () => {
  switch (periodType.value) {
    case 'week':
      return '周'
    case 'month':
      return '月'
    case 'year':
      return '年'
    default:
      return '期间'
  }
}

// 格式化数字
const formatNumber = (num: number) => {
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}
</script>

<style scoped>
.statistics-page {
  padding: 20px;
}

.header-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
}

.overview-section,
.charts-section,
.content-stats-section,
.popular-content-section,
.user-distribution-section {
  margin-bottom: 20px;
}

.stat-card {
  height: 100%;
}

.stat-card-content {
  padding: 8px;
}

.stat-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.stat-card-title {
  font-size: 16px;
  color: rgba(0, 0, 0, 0.6);
}

.stat-card-icon {
  font-size: 24px;
  color: var(--td-brand-color);
}

.stat-card-value {
  font-size: 28px;
  font-weight: 500;
  margin-bottom: 16px;
}

.stat-card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
}

.stat-trend {
  display: flex;
  align-items: center;
  gap: 4px;
}

.stat-trend.up {
  color: #00a870;
}

.stat-trend.down {
  color: #e34d59;
}

.stat-detail {
  display: flex;
  gap: 12px;
  font-size: 13px;
  color: rgba(0, 0, 0, 0.6);
}

.stat-period {
  font-size: 13px;
  color: rgba(0, 0, 0, 0.4);
}

.chart-card,
.list-card {
  height: 100%;
}
</style> 